import 'dart:async';

import 'package:flutter/material.dart';
import 'package:wanflutter/manager/app_manager.dart';
import 'package:wanflutter/ui/widget/article_item.dart';

import '../../event/events.dart';
import '../../http/api.dart';

class ArticleCollectPage extends StatefulWidget {
  @override
  State<ArticleCollectPage> createState() => _ArticleCollectPageState();
}

class _ArticleCollectPageState extends State<ArticleCollectPage>
  with AutomaticKeepAliveClientMixin { //with 等于多继承功能

  bool _isHidden =false;

  ///滑动控制器
  ScrollController _controller = new ScrollController();

  List _collects =[];
  var curPage = 0;

  var pageCount;

  late StreamSubscription<CollectEvent> collectEventListen;


  @override
  void initState() {
    super.initState();
    /// state初始化时添加两个监听器
    _controller.addListener(() {
      ///获得SrollController监听控件可以滚动的最大范围
      var maxScroll = _controller.position.maxScrollExtent;

      ///获得当前位置的像素值
      var pixels = _controller.position.pixels;

      ///当滑动位置到底部，加载更多数据
      if(maxScroll == pixels && curPage < pageCount) {
        _getCollects();
      }
    });
    collectEventListen = AppManager.eventBus.on<CollectEvent>().listen((event) {
      ///页面没有被dispose
      if(mounted){
        //取消收藏
        if(!event.collect) {
          _collects.removeWhere((element){ // 当监听到的信息id和
            return element['id'] == event.id;
          });
        }
      }
    });
    _getCollects();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 网络数据下载中，转圈屏蔽
        Offstage(
          offstage: _isHidden,
          child: Center(
            child: CircularProgressIndicator(),
          ),
        ),
        Offstage(
          ///不为空则隐藏
          offstage: _collects.isNotEmpty || !_isHidden,
          child: Text("(＞﹏＜) 你还没有收藏任何内容......"),
        ),
        Offstage(
          offstage: _collects.isEmpty,
          child: RefreshIndicator(
            onRefresh: ()=>_getCollects(true),
            child: ListView.builder(
              //总是能滑动，因为数据少，listview无法滑动，
              //RefreshIndicator 就无法更新
              physics:AlwaysScrollableScrollPhysics(),
              itemCount: _collects.length,
              itemBuilder: (context, i) => _buildItem(i),
              controller: _controller,
            ),
          ),
        )
      ],
    );
  }


  @override
  void dispose() {
    collectEventListen.cancel();
    _controller.dispose();
    super.dispose();
  }

  ///刷新当前的收藏页
  _getCollects([bool refresh=false]) async {
    if(refresh) {
      curPage = 0;
    }
    var result = await Api.getArticleCollects(curPage);
    if (result != null) {
      if(curPage == 0) {
        _collects.clear();
      }
      curPage++;
      var data = result['data'];
      pageCount = data['pageCount'];
      _collects.addAll(data['datas']);
      _isHidden = true;
      setState(() {

      });
    }
  }

  @override
  // tab切换不重置
  bool get wantKeepAlive => true;

  _buildItem(int i) {
    //只收藏站内
    _collects[i]['id'] = _collects[i]['originId'];
    _collects[i]['collect'] = true;  //字典？
    return ArticleItem(_collects[i]);
  }
}
